import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  TreeSelect,
  Modal,
  Transfer,
} from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import { text_check, post_axios } from "../../utils";
import UserTable from "../../modules/userTable";

export default function Circuit(props) {
  const { t } = useTranslation();
  const { Option } = Select;
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);
  const [circuit_name, setCircuit_name] = useState("");
  const [circuit_status, setCircuit_status] = useState("");
  const [com_ids_par, setCom_ids_par] = useState([]);
  const [circuit_list, setCcircuit_list] = useState([]);

  const getData = async (newPage, newRows) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      name: circuit_name,
      status: circuit_status,
      com_ids_par: JSON.parse(JSON.stringify(com_ids_par)),
    };
    setSpinning(true);
    let res = await post_axios("circuit_manager", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setCcircuit_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("market.circuit_name"),
      dataIndex: "circuit",
      align: "center",
    },
    {
      title: t("market.organization"),
      align: "center",
      width: 300,
      render: (_, record) => (
        <>{record.com2 + "-" + record.com3 + "-" + record.com}</>
      ),
    },
    {
      title: t("common.status"),
      align: "center",
      width: 100,
      render: (_, record) => (
        <>
          {record.status === "0" ? (
            <span>{t("common.enable")}</span>
          ) : (
            <span style={{ color: "red" }}>{t("common.disable")}</span>
          )}
        </>
      ),
    },
    {
      title: t("market.operator"),
      dataIndex: "username",
      align: "center",
    },
    {
      title: t("market.operation_time"),
      dataIndex: "u_time",
      width: 200,
      align: "center",
    },
  ];

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});

  const tableRowClick = async (row) => {
    setClickRowKey(row.circuit_id);
    setclickRow(row);
    setSpinning(true);
    await get_circuit_user_data(row);
    await get_circuit_project_data(row);
    setSpinning(false);
  };

  const search_data = () => {
    setPage(1);
    initData(1);
  };

  const initData = (page, rows) => {
    setClickRowKey("");
    setclickRow([]);
    setCircuit_user_list([]);
    setCircuit_project_list([]);
    getData(page, rows);
  };

  const [circuit_user_list, setCircuit_user_list] = useState();
  const [circuit_project_list, setCircuit_project_list] = useState([]);
  const get_circuit_user_data = async (row) => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      com_id: row ? row.circuit_id : clickRowKey,
    };
    let res = await post_axios("circuit_manager", "m_query_user", upMsg);
    if (!res) return;
    setCircuit_user_list(res.data_rows.rows);
  };

  const get_circuit_project_data = async (row) => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      circuit_id: row ? row.circuit_id : clickRowKey,
    };
    let res = await post_axios("circuit_manager", "m_query_project", upMsg);
    if (!res) return;
    setCircuit_project_list(res.data_rows.rows);
  };

  // 获取组织列表
  const [com_list, setCom_list] = useState([]);
  const get_com_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_com_id",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setCom_list(res.data_rows.rows);
  };

  // 获取项目列表
  const [project_list, setProject_list] = useState([]);
  const get_project_data = async () => {
    let upMsg = {
      page: 1,
      rows: 1000,
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_project",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    const receiveRows = res.data_rows.rows.map((item) => {
      return {
        key: item.project_id,
        title: item.project,
      };
    });
    setProject_list(receiveRows);
  };
  // 添加/修改
  const [edit_type, setEdit_type] = useState("");
  const [editDialogshow, setEditDialogshow] = useState(false);
  const [editDialogtitle, setEditDialogtitle] = useState("");

  const [edit_circuit_name, setEdit_circuit_name] = useState("");
  const [edit_circuit_status, setEdit_circuit_status] = useState("0");
  const [edit_circuit_com_id, setEdit_circuit_com_id] = useState("");
  const [project_ids_checkList, setProject_ids_checkList] = useState([]);
  const edit_circuit_dialog_show = (value) => {
    setEdit_type(value);
    if (value === "add") {
      setEditDialogtitle(t("common.add") + " " + t("market.project"));
      setEdit_circuit_name("");
      setEdit_circuit_status("0");
      setEdit_circuit_com_id("");
      setProject_ids_checkList([]);
      setEditDialogshow(true);
    } else {
      if (clickRowKey === "") {
        message.warning({
          content: t("system_manager.choose_one_project"),
        });
        return;
      }

      setEditDialogtitle(t("common.change") + " " + t("market.project"));
      const { circuit, status, com_id } = clickRow;
      setEdit_circuit_name(circuit);
      setEdit_circuit_status(status);
      setEdit_circuit_com_id(com_id);
      setProject_ids_checkList(
        circuit_project_list.map((item) => item.project_id)
      );

      setEditDialogshow(true);
    }
  };
  const editConfirm = async () => {
    if (edit_circuit_name === "") {
      message.warning({
        content: t("market.enter_circuit_name"),
      });
      return;
    }
    if (edit_circuit_com_id === "") {
      message.warning({
        content: t("market.select_organization"),
      });
      return;
    }
    let upMsg = {
      com_id: edit_circuit_com_id,
      name: edit_circuit_name,
      status: edit_circuit_status,
      array_project_ids_select: project_ids_checkList,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let action = "m_add";
    if (edit_type.value == "change") {
      action = "m_modify";
      upMsg["circuit_id"] = clickRowKey.value;
    }
    setSpinning(true);
    let res = await post_axios("circuit_manager", action, upMsg);
    setSpinning(false);
    if (!res) return;
    message.success({
      message: editDialogtitle + " " + t("common.successfully"),
    });
    setEditDialogshow(false);
    search_data();
  };

  function treeNodeItem(node) {
    const { TreeNode } = TreeSelect;
    if (node.children) {
      return (
        <TreeNode
          value={node.com_id}
          title={node.com}
          key={node.com_id}
          selectable={node.grade === 4}
          disabled={node.grade !== 4}
        >
          {node.children.map((child) => {
            return treeNodeItem(child);
          })}
        </TreeNode>
      );
    } else {
      return (
        <TreeNode
          value={node.com_id}
          title={node.com}
          key={node.com_id}
          selectable={node.grade === 4}
          disabled={node.grade !== 4}
        />
      );
    }
  }

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("circuit_manager")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
    });
    if (user_grade < 70) {
      get_com_data();
    }
    get_project_data();
  }, []);
  return (
    <>
      <div className="circuit_manager modules">
        <div className="screen_ipt">
          <div className="ipt_box">
            <div className="ipt_box_title">{t("market.circuit_name")}</div>
            <Input
              placeholder=" "
              value={circuit_name}
              size="small"
              allowClear={true}
              onChange={(e) => setCircuit_name(e.target.value)}
            />
          </div>
          <div className="ipt_box">
            <div className="ipt_box_title">{t("common.status")}</div>
            <Select
              size="small"
              placeholder=" "
              allowClear={true}
              options={[
                {
                  label: t("common.enable"),
                  value: "0",
                  key: "0",
                },
                {
                  label: t("common.disable"),
                  value: "1",
                  key: "1",
                },
              ]}
              value={circuit_status}
              onChange={(value) => setCircuit_status(value)}
            />
          </div>
          {user_grade < 70 ? (
            <div className="ipt_box ipt_box_long">
              <div className="ipt_box_title">{t("market.organization")}</div>
              <TreeSelect
                value={com_ids_par}
                treeData={com_list}
                allowClear={true}
                size="small"
                multiple
                treeCheckStrictly={true}
                fieldNames={{
                  label: "com",
                  value: "com_id",
                  children: "children",
                }}
                placeholder=" "
                treeCheckable={true}
                onChange={(newValue) => setCom_ids_par(newValue)}
              />
            </div>
          ) : (
            ""
          )}
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_circuit_dialog_show("add")}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_circuit_dialog_show("change")}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "49.8vw",
            }}
          >
            <Table
              dataSource={circuit_list}
              size="small"
              bordered
              columns={columns}
              rowKey="circuit_id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => tableRowClick(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.circuit_id == clickRowKey) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
          <div
            className="noPage-table"
            style={{
              width: "9.8vw",
            }}
          >
            <Table
              dataSource={circuit_project_list}
              size="small"
              bordered
              columns={[
                {
                  title: t("market.project"),
                  dataIndex: "project",
                  align: "center",
                },
              ]}
              rowKey="project_id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              rowHoverable={false}
              pagination={false}
            />
          </div>

          <div
            className="noPage-table"
            style={{
              width: "39.9vw",
            }}
          >
            <UserTable
              user_list={circuit_user_list}
              tableHeight={tableHeight}
            />
          </div>
        </div>
      </div>

      <Modal
        title={editDialogtitle}
        open={editDialogshow}
        onOk={editConfirm}
        onCancel={() => setEditDialogshow(false)}
        classNames={{ body: "edit_dialog_body", wrapper: "edit_900_style" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box short_title">
          <div className="ipt_box_title">{t("market.circuit_name")}</div>
          <Input
            placeholder=" "
            value={edit_circuit_name}
            onChange={(e) => setEdit_circuit_name(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box short_title">
          <div className="ipt_box_title">{t("common.status")}</div>
          <Select
            placeholder=" "
            allowClear={false}
            options={[
              {
                label: t("common.enable"),
                value: "0",
                key: "0",
              },
              {
                label: t("common.disable"),
                value: "1",
                key: "1",
              },
            ]}
            value={edit_circuit_status}
            onChange={(value) => setEdit_circuit_status(value)}
          />
        </div>
        <div className="dialog_ipt_box short_title">
          <div className="ipt_box_title">{t("market.organization")}</div>
          <TreeSelect
            value={edit_circuit_com_id}
            placeholder=" "
            popupMatchSelectWidth={300}
            onSelect={(value, node, extra) => {
              return setEdit_circuit_com_id(value);
            }}
          >
            {com_list.map((item) => {
              return treeNodeItem(item);
            })}
          </TreeSelect>
        </div>
        <div className="dialog_ipt_box short_title" style={{ width: "700px" }}>
          <div className="ipt_box_title">{t("market.project")}</div>

          <div className="transfer_box">
            <Transfer
              dataSource={project_list}
              targetKeys={project_ids_checkList}
              onChange={(newValue) => setProject_ids_checkList(newValue)}
              render={(item) => item.title}
              oneWay={true}
              showSearch
              showSelectAll
              pagination={false}
            />
          </div>
        </div>
      </Modal>
    </>
  );
}
